<template>
  <div>
    <div class="exhibition-area">
      <!-- 左侧堆叠柱状图 -->
      <div class="enter">
        <div id="stackedBarChart" style="width: 100%; height: 100%;"></div>
      </div>

      <!-- 箭头 -->
      <div class="custom-arrow">
        <img src="@/assets/images/arrow.jpg" alt="Arrow">
      </div>

      <!-- 资金池环形图 -->
      <div class="pond" style="width: 100%; max-width: 500px; height: 30vh;"></div>

      <!-- 箭头 -->
      <div class="custom-arrow">
        <img src="@/assets/images/arrow.jpg" alt="Arrow">
      </div>

      <!-- 右侧柱状图 -->
      <div class="out">
        <div id="barChart" style="width: 100%; height: 100%;"></div>
      </div>
    </div>

    <!-- 利润分析 -->
    <div class="profit">
      <div class="profit-title">利润分析</div>
      <div class="table-container">
        <div class="table-wrapper">
          <div class="table-title">用户提币交易</div>
          <el-table
            :data="memberWithdrawCryptoByTransferOutData"
            :span-method="memberWithdrawCryptoSpanMethod"
            border
            style="width: 100%"
            max-height="400">
            <el-table-column prop="chain" label="公链" align="center"></el-table-column>
            <el-table-column prop="ccy" label="币种" align="center"></el-table-column>
            <el-table-column prop="total" label="累计交易" align="center"></el-table-column>
            <el-table-column prop="theyProfit" label="第三方利润" align="center"></el-table-column>
            <el-table-column prop="usProfit" label="平台利润" align="center"></el-table-column>
          </el-table>
        </div>

        <div class="table-wrapper">
          <div class="table-title">用户提现交易</div>
          <el-table
            :data="memberWithdrawCryptoByTransferFiatData"
            :span-method="memberWithdrawSpanMethod"
            border
            style="width: 100%"
            max-height="400">
            <el-table-column prop="chain" label="公链" align="center"></el-table-column>
            <el-table-column prop="ccy" label="币种" align="center"></el-table-column>
            <el-table-column prop="total" label="累计交易" align="center"></el-table-column>
            <el-table-column prop="usProfit" label="平台利润" align="center"></el-table-column>
          </el-table>
        </div>

        <div class="table-wrapper">
          <div class="table-title">系统提币交易</div>
          <el-table
            :data="systemWithdrawCryptoByTransferOutData"
            :span-method="systemWithdrawCryptoSpanMethod"
            border
            style="width: 100%"
            max-height="400">
            <!-- 表格列定义 -->
            <el-table-column prop="chain" label="公链" align="center"></el-table-column>
            <el-table-column prop="withdrawalMoneyCcy" label="币种" align="center"></el-table-column>
            <el-table-column prop="total" label="累计交易" align="center"></el-table-column>
            <el-table-column prop="commission" label="累计手续费" align="center"></el-table-column>
          </el-table>
        </div>

        <div class="table-wrapper">
          <div class="table-title">系统提现交易</div>
          <el-table
            :data="systemWithdrawSpanMethod"
            border
            style="width: 100%"
            max-height="400">
            <!-- 表格列定义 -->
            <el-table-column prop="withdrawalMoneyCcy" label="提现币种" align="center"></el-table-column>
            <el-table-column prop="payoutMoneyCcy" label="目标币种" align="center"></el-table-column>
            <el-table-column prop="total" label="提现金额" align="center"></el-table-column>
            <el-table-column prop="commission" label="累计手续费" align="center"></el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 条件统计年、月、日 -->
    <div class="condition-stat">
      <div class="condition">
        <div class="condition-item">
          <span>公链：</span>
          <el-select style="width: 160px" v-model="queryParam.chain">
            <el-option
              v-for="item in options"
              :key="item.chain"
              :label="item.chain"
              :value="item.chain"
            />
          </el-select>
        </div>
        <div class="condition-item">
          <span>年：</span>
          <el-date-picker
            v-model="queryParam.year"
            type="year"
            value-format="yyyy"
            placeholder="选择年份"
            @change="handleYearChange"
            style="width: 120px"
          />
        </div>
        <div class="condition-item centered-button">
          <el-button type="primary" plain @click="refresh">刷新 <i class="el-icon-refresh"></i></el-button>
        </div>
      </div>

      <!-- 饼图与柱状图容器 -->
      <div class="container-condition-stat">
        <div id="pieChart" style="width: 25%; height: 30vh;"></div>
        <div id="stackedBarChartLeft" style="width: 75%; height: 30vh;"></div>
      </div>
    </div>

    <div class="condition-stat">
      <div class="condition">
        <div class="condition-item">
          <span>出金类型：</span>
          <el-select clearable v-model="outSelectedTransferCcy" placeholder="请选择出金类型" style="width: 120px">
            <el-option label="提币交易" value="transfer-out"></el-option>
            <el-option label="提现交易" value="transfer-fiat"></el-option>
          </el-select>
        </div>
        <div class="condition-item">
          <span>公链：</span>
          <el-select style="width: 160px" v-model="outSelectedChain">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.chain"
              :value="item.id"
            />
          </el-select>
        </div>
        <div class="condition-item">
          <span>年：</span>
          <el-date-picker
            v-model="outSelectedYear"
            type="year"
            placeholder="选择年份"
            @change="handleYearChange"
            style="width: 120px"
          />
        </div>
        <div class="condition-item centered-button">
          <el-button type="primary" plain>刷新 <i class="el-icon-refresh"></i></el-button>
        </div>
      </div>

      <!-- 出金饼图与柱状图容器 -->
      <div class="container-condition-stat">

      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts';
import {
  cryptoDepositTotalSta,
  cryptoPoolTotalSta,
  cryptoWithdrawTotalSta,
  cryptoMemberWithdrawProfitSta,
  cryptoDepositTotalByChainAndYearSta
} from '@/api/triones/financeSta'

import {optionSelect} from "@/api/triones/chainAndCcy";

export default {
  name: "LeptageBill",
  data() {
    return {
      cryptoDepositTotalXAxisData: [],
      cryptoDepositTotalLegendData: [],
      cryptoDepositTotalSeriesData: [],
      cryptoWithdrawTotalXAxisData: [],
      cryptoWithdrawTotalLegendData: [],
      cryptoWithdrawTotalSeriesData: [],
      queryParam: {
        chain: '',
        year: ''
      },
      selectedMonth: null,
      outSelectedTransferCcy: 'transfer-out',
      outSelectedChain: null,
      outSelectedYear: null,
      memberWithdrawCryptoByTransferOutData: [],
      memberWithdrawCryptoByTransferFiatData: [],
      systemWithdrawCryptoByTransferOutData: [],
      systemWithdrawSpanMethod: [],
      options: [],
      cryptoDepositTotalByChainAndYearSta: [],
      initConditionStatPieChartData: [],
      initConditionStatPieChartLegendData: [],

      series1Data: [120, 130, 100, 150, 160, 140, 180, 200, 190, 170, 150, 130],
      series2Data: [80, 90, 70, 100, 110, 90, 120, 130, 110, 100, 90, 80],
      tableData: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyword: undefined
      },
    };
  },
  mounted() {
    this.getCreateYear();
    this.getChainList();
    this.getCryptoDepositTotalSta();
    this.getCryptoPoolTotalSta();
    this.getCryptoWithdrawTotalSta();
    this.getCryptoMemberWithdrawProfitByTransferOutSta();
    this.getCryptoMemberWithdrawProfitByTransferFiatSta();
    this.getCryptoDepositTotalByChainAndYearSta();


    this.initPieChart();
    this.setupClickEvent();
    this.initStackedBarChart();       // 初始化左侧堆叠柱状图
    this.initStackedBarChartRight();  // 初始化右侧堆叠柱状图

    // 新增：初始化条件统计区域的堆叠柱状图
    this.initConditionStatBarChartLeft();

    window.addEventListener('resize', this.handleResize);
  },
  methods: {
    refresh() {
      this.getCryptoDepositTotalByChainAndYearSta();
    },
    /** 获取当前年份 */
    getCreateYear() {
      var currentDate = new Date();
      this.queryParam.year = currentDate.getFullYear() + '';
    },
    /** 查询字典类型列表 */
    getChainList() {
      optionSelect().then(response => {
        this.options = response.data;
        this.outSelectedChain = this.options[0].id;
      });
    },

    memberWithdrawCryptoSpanMethod({row, column, rowIndex, columnIndex}) {
      const spanArr = [];
      let pos = 0;
      this.memberWithdrawCryptoByTransferOutData.forEach((item, index) => {
        if (index === 0) {
          // 第一行直接加入合并数组
          spanArr.push(1);
          pos = 0;
        } else {
          // 比较当前行与前一行的chain属性
          if (item.chain === this.memberWithdrawCryptoByTransferOutData[index - 1].chain) {
            // 相同则合并行数加1，当前行不显示
            spanArr[pos] += 1;
            spanArr.push(0);
          } else {
            // 不同则开始新的分组
            spanArr.push(1);
            pos = index;
          }
        }
      });
      if (columnIndex === 0) {
        const rowspan = spanArr[rowIndex];
        if (rowspan <= 0) {
          return {rowspan: 0, colspan: 0};
        }
        return {rowspan, colspan: 1};
      }
      return {rowspan: 1, colspan: 1};
    },

    memberWithdrawSpanMethod({row, column, rowIndex, columnIndex}) {
      const spanArr = [];
      let pos = 0;
      this.memberWithdrawCryptoByTransferFiatData.forEach((item, index) => {
        if (index === 0) {
          // 第一行直接加入合并数组
          spanArr.push(1);
          pos = 0;
        } else {
          // 比较当前行与前一行的chain属性
          if (item.chain === this.memberWithdrawCryptoByTransferFiatData[index - 1].chain) {
            // 相同则合并行数加1，当前行不显示
            spanArr[pos] += 1;
            spanArr.push(0);
          } else {
            // 不同则开始新的分组
            spanArr.push(1);
            pos = index;
          }
        }
      });
      if (columnIndex === 0) {
        const rowspan = spanArr[rowIndex];
        if (rowspan <= 0) {
          return {rowspan: 0, colspan: 0};
        }
        return {rowspan, colspan: 1};
      }
      return {rowspan: 1, colspan: 1};
    },

    systemWithdrawCryptoSpanMethod({row, column, rowIndex, columnIndex}) {
      const spanArr = [];
      let pos = 0;
      this.systemWithdrawCryptoByTransferOutData.forEach((item, index) => {
        if (index === 0) {
          // 第一行直接加入合并数组
          spanArr.push(1);
          pos = 0;
        } else {
          // 比较当前行与前一行的chain属性
          if (item.chain === this.systemWithdrawCryptoByTransferOutData[index - 1].chain) {
            // 相同则合并行数加1，当前行不显示
            spanArr[pos] += 1;
            spanArr.push(0);
          } else {
            // 不同则开始新的分组
            spanArr.push(1);
            pos = index;
          }
        }
      });
      if (columnIndex === 0) {
        const rowspan = spanArr[rowIndex];
        if (rowspan <= 0) {
          return {rowspan: 0, colspan: 0};
        }
        return {rowspan, colspan: 1};
      }
      return {rowspan: 1, colspan: 1};
    },
    getCryptoDepositTotalSta() {
      cryptoDepositTotalSta().then(res => {
        this.cryptoDepositTotalLegendData = res.data.ccyList;
        this.cryptoDepositTotalXAxisData = res.data.chainStrList;
        this.cryptoDepositTotalSeriesData = res.data.ccyList.map((item, index) => {
          return {
            name: item,
            type: 'bar',
            stack: '总量',
            barWidth: 50,
            label: {show: true},
            data: res.data.ccyTotalList[index]
          }
        });
        this.initStackedBarChart();
      })
    },
    initStackedBarChart() {
      const chartDom = document.getElementById('stackedBarChart');
      if (!chartDom) return;
      const myChart = echarts.init(chartDom);
      const option = {
        title: {text: '累计入金', left: 'center'},
        tooltip: {trigger: 'axis', axisPointer: {type: 'shadow'}},
        legend: {
          data: this.cryptoDepositTotalLegendData,
          top: 30
        },
        grid: {
          top: 80,
          left: '5%',
          right: '10%',
          bottom: '4%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          name: '公链',
          nameLocation: 'end',
          data: this.cryptoDepositTotalXAxisData
        },
        yAxis: {
          type: 'value',
          name: '数量（个）',
          nameLocation: 'end'
        },
        series: this.cryptoDepositTotalSeriesData
      };
      myChart.setOption(option);
    },

    getCryptoPoolTotalSta() {

    },

    getCryptoWithdrawTotalSta() {
      cryptoWithdrawTotalSta().then(res => {
        this.cryptoWithdrawTotalLegendData = res.data.ccyList;
        this.cryptoWithdrawTotalXAxisData = res.data.chainStrList;
        this.cryptoWithdrawTotalSeriesData = res.data.ccyList.map((item, index) => {
          return {
            name: item,
            type: 'bar',
            stack: '总量',
            barWidth: 50,
            label: {show: true},
            data: res.data.ccyTotalList[index]
          }
        });
        this.initStackedBarChartRight();
      })
    },
    initStackedBarChartRight() {
      const chartDom = document.getElementById('barChart');
      if (!chartDom) return;

      const myChart = echarts.init(chartDom);

      const option = {
        title: {text: '累计出金', left: 'center'},
        tooltip: {trigger: 'axis', axisPointer: {type: 'shadow'}},
        legend: {
          data: this.cryptoWithdrawTotalLegendData,
          top: 30
        },
        grid: {
          top: 80,
          left: '5%',
          right: '10%',
          bottom: '4%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          name: '公链',
          nameLocation: 'end',
          data: this.cryptoWithdrawTotalXAxisData
        },
        yAxis: {
          type: 'value',
          name: '数量（个）',
          nameLocation: 'end'
        },
        series: this.cryptoWithdrawTotalSeriesData
      };
      myChart.setOption(option);
    },

    getCryptoMemberWithdrawProfitByTransferOutSta() {
      cryptoMemberWithdrawProfitSta('transfer-out').then(res => {
        this.memberWithdrawCryptoByTransferOutData = res.data.list;
      })
    },

    getCryptoMemberWithdrawProfitByTransferFiatSta() {
      cryptoMemberWithdrawProfitSta('transfer-fiat').then(res => {
        this.memberWithdrawCryptoByTransferFiatData = res.data.list;
      })
    },

    getCryptoDepositTotalByChainAndYearSta() {
      cryptoDepositTotalByChainAndYearSta(this.queryParam).then(res => {
        this.initConditionStatPieChartData = res.data.list;
        this.initConditionStatPieChartLegendData = res.data.legendList;
        // 入金占比（饼图）
        this.initConditionStatPieChart();
      })
    },
    initConditionStatPieChart() {
      const chartDom = document.getElementById('pieChart');
      if (!chartDom) return;
      const myChart = echarts.init(chartDom);
      const option = {
        title: {
          text: '入金占比',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a}<br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: this.initConditionStatPieChartLegendData
        },
        series: [{
          name: '数据',
          type: 'pie',
          radius: '50%',
          data: this.initConditionStatPieChartData,
          label: {
            show: true,
            position: 'outside',
            formatter: '{b}: {c} ({d}%)'
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      myChart.setOption(option);
    },

    handleQuery() {

    },
    resetQuery() {

    },
    initProfitPieChart(chartId, titleText, pieData) {
      const chartDom = document.getElementById(chartId);
      if (!chartDom) return;

      const myChart = echarts.init(chartDom);

      const option = {
        title: {
          text: titleText,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a}<br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: pieData.map(item => item.name)
        },
        series: [{
          name: '数据',
          type: 'pie',
          radius: '50%',
          data: pieData,
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      };
      myChart.setOption(option);
    },

    handleYearChange(year) {
      console.log('Selected year:', year);
      console.log('Selected:', this.selectedYear);
      this.updateConditionStatBarChartLeft(year);
    },

    updateConditionStatBarChartLeft(year) {
      const chartDom = document.getElementById('stackedBarChartLeft');
      if (!chartDom) return;

      const myChart = echarts.getInstanceByDom(chartDom);

      let newData;
      if (year) {
        newData = [100, 150, 120]; // 示例数据
      } else {
        newData = [120, 130, 100]; // 默认数据
      }

      myChart.setOption({
        series: [{data: newData}]
      });
    },


    initPieChart() {
      const chartDom = document.querySelector('.pond');
      if (!chartDom) return;

      const myChart = echarts.init(chartDom);

      const option = {
        title: {
          text: 'crypto 资金池',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a}<br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: ['A', 'B', 'C', 'D', 'E']
        },
        series: [
          {
            name: '外环数据',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {show: false, position: 'center'},
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            data: [
              {value: 335, name: 'A'},
              {value: 310, name: 'B'},
              {value: 274, name: 'C'},
              {value: 235, name: 'D'},
              {value: 400, name: 'E'}
            ]
          },
          {
            name: '内环数据',
            type: 'pie',
            radius: ['0%', '30%'],
            label: {show: false},
            data: [
              {value: 100, name: 'A1'},
              {value: 150, name: 'A2'},
              {value: 85, name: 'A3'}
            ],
            itemStyle: {
              borderRadius: 5,
              borderColor: '#fff',
              borderWidth: 2
            }
          }
        ]
      };

      myChart.setOption(option);
    },

    setupClickEvent() {
      const chartDom = document.querySelector('.pond');
      if (!chartDom) return;

      const myChart = echarts.getInstanceByDom(chartDom);

      myChart.on('click', (params) => {
        if (params.seriesType === 'pie' && params.data && params.event?.target?.style) {
          let innerData = [];
          switch (params.name) {
            case 'A':
              innerData = [{value: 100, name: 'A1'}, {value: 150, name: 'A2'}, {value: 85, name: 'A3'}];
              break;
            case 'B':
              innerData = [{value: 120, name: 'B1'}, {value: 90, name: 'B2'}];
              break;
            case 'C':
              innerData = [{value: 80, name: 'C1'}, {value: 60, name: 'C2'}, {value: 30, name: 'C3'}];
              break;
            default:
              innerData = [{value: 50, name: '默认'}];
          }

          myChart.setOption({
            series: [
              {}, // 外环不变
              {data: innerData} // 更新内环数据
            ]
          });
        }
      });
    },

    initConditionStatBarChartLeft() {
      const chartDom = document.getElementById('stackedBarChartLeft');
      if (!chartDom) return;

      const myChart = echarts.init(chartDom);

      const option = {
        title: {text: '入金统计', left: 'center'},
        tooltip: {trigger: 'axis', axisPointer: {type: 'shadow'}},
        legend: {
          data: ['系列1', '系列2'],
          top: 30
        },
        grid: {
          top: 80,
          left: '8%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: Array.from({length: 12}, (_, i) => `${i + 1}月`),
          axisLabel: {rotate: 45}
        },
        yAxis: {
          type: 'value',
          name: '金额（元）',
          nameLocation: 'end',
          nameGap: 30,
          axisLabel: {formatter: '{value} 元'}
        },
        series: [
          {
            name: '系列1',
            type: 'bar',
            stack: '总量',
            barWidth: 20,
            label: {show: true, position: 'insideTop'},
            data: this.series1Data
          },
          {
            name: '系列2',
            type: 'bar',
            stack: '总量',
            barWidth: 20,
            label: {show: true, position: 'insideTop'},
            data: this.series2Data
          }
        ]
      };

      myChart.setOption(option);
    },

    handleResize() {
      const stackedChart = echarts.getInstanceByDom(document.getElementById('stackedBarChart'));
      const barChart = echarts.getInstanceByDom(document.getElementById('barChart'));
      const pieChart = echarts.getInstanceByDom(document.querySelector('.pond'));
      const conditionStatLeftChart = echarts.getInstanceByDom(document.getElementById('stackedBarChartLeft'));
      const conditionStatPieChart = echarts.getInstanceByDom(document.getElementById('pieChart'));

      if (stackedChart) stackedChart.resize();
      if (barChart) barChart.resize();
      if (pieChart) pieChart.resize();
      if (conditionStatLeftChart) conditionStatLeftChart.resize();
      if (conditionStatPieChart) conditionStatPieChart.resize();
    }
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
  }
};
</script>

<style scoped lang="scss">
.exhibition-area {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 30px;

  > .enter,
  > .pond,
  > .out {
    flex: 1 1 30%;
    min-width: 280px;
    max-width: 500px;
    margin-bottom: 20px;
  }
}

.condition-stat {
  width: 100%;
  padding: 20px;
  background-color: #eeeff1;

  .condition {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    justify-content: start;
    margin-bottom: 20px;

    .condition-item {
      padding-right: 20px;
      margin-bottom: 10px;
    }
  }

  .container-condition-stat {
    display: flex;
    gap: 10px;
    width: 100%;
  }
}

.custom-arrow {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 15px;

  img {
    width: 100%;
    max-width: 40px;
    height: auto;
  }
}

.enter,
.out {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 30vh;
  min-height: 200px;
}

@media screen and (max-width: 768px) {
  .exhibition-area,
  .condition-stat {
    padding: 10px;
  }

  .enter,
  .pond,
  .out,
  .container-condition-stat {
    flex: 1 1 90%;
    margin-bottom: 20px;
  }

  .custom-arrow {
    padding: 0 10px;
  }
}

.centered-button {
  display: flex;
  align-items: center;
}

.profit {
  background-color: #f9f9fb;

  .profit-title {
    padding: 20px;
    text-align: center;
    font-size: 20px;
    font-weight: bold;
  }

  .table-container {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-top: 20px;
    padding: 0 20px;
  }

  .table-wrapper {
    flex: 0 0 calc(50% - 10px);
    box-sizing: border-box;
    margin-bottom: 20px;

    .table-title {
      padding: 10px;
      font-size: 16px;
      font-weight: bold;
      text-align: center;
      background-color: #1ab394;
    }
  }

  @media screen and (max-width: 768px) {
    .table-wrapper {
      flex: 0 0 100%;
      margin-bottom: 20px;
    }
  }
}

</style>
